package com.sky.service.common.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.exception.DishExistsException;
import com.sky.exception.ParamsIllegalException;
import com.sky.mapper.common.DishFlavorMapper;
import com.sky.mapper.common.DishMapper;
import com.sky.mapper.admin.SetmealDishMapper;
import com.sky.pojo.Dish;
import com.sky.pojo.DishFlavor;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.common.DishService;
import com.sky.vo.DishVO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 菜品管理业务实现类
 *
 * @Author: Zhy
 * @Date: 2025-01-19 21:28
 * @Version: 1.0
 */
@Service
@RequiredArgsConstructor
public class DishServiceImpl implements DishService {
	private final DishMapper dishMapper;
	private final DishFlavorMapper dishFlavorMapper;
	private final SetmealDishMapper setmealDishMapper;

	/**
	 * 添加菜品及其口味
	 *
	 * @return:
	 * @param:
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Result<String> addDish(DishDTO dishDTO) {
		// 参数校验
		if (Objects.isNull(dishDTO) ||
			Objects.isNull(dishDTO.getCategoryId()) ||
			StringUtils.isBlank(dishDTO.getName()) ||
			Objects.isNull(dishDTO.getPrice()) ||
			StringUtils.isBlank(dishDTO.getImage())) {
			throw new ParamsIllegalException("新增菜品出错了，请重新输入");
		}

		// 业务处理
		// 处理产品是否存在
		Integer count = dishMapper.countByName(dishDTO.getName());
		if (count > 0) {
			throw new DishExistsException("菜品已存在");
		}
		Dish dish = new Dish();
		BeanUtils.copyProperties(dishDTO, dish);
		dishMapper.insert(dish);

		// 为每一个口味添加菜品 id
		List<DishFlavor> flavors = dishDTO.getFlavors();
		if (Objects.isNull(flavors)) {
			return Result.success("添加成功");
		}
		flavors.forEach(flavor -> flavor.setDishId(dish.getId()));
		dishFlavorMapper.insertDishFlavor(flavors);

		return Result.success("添加成功");
	}

	/**
	 * 条件分页查询
	 *
	 * @return:
	 * @param:
	 */
	@Override
	public Result<PageResult<DishVO>> pageQueryDish(DishPageQueryDTO dishPageQueryDTO) {
		// 参数校验

		// 业务处理
		PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
		Page<DishVO> page = dishMapper.pageQueryDish(dishPageQueryDTO);

		PageResult<DishVO> pageResult = new PageResult<>(page.getTotal(), page.getResult());
		return Result.success(pageResult);
	}

	/**
	 * 根据ID删除菜品
	 *
	 * @return:
	 * @param:
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Result<String> deleteDishById(List<Long> ids) {
		// 参数校验
		if (Objects.isNull(ids) || ids.isEmpty()) {
			throw new ParamsIllegalException("删除失败，被删除的菜品不能为空");
		}

		// 业务处理
		// 1. 启售状态的菜品不能删除
		Long count = dishMapper.countDishByStatus(ids, 1);
		if (count > 0) {
			throw new DishExistsException(MessageConstant.DISH_ON_SALE);
		}
		// 2. 被套餐关联的菜品不能删除
		count = setmealDishMapper.countSetmealDishByIds(ids);
		if (count > 0) {
			throw new DishExistsException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
		}
		// 3. 删除菜品及其口味
		dishMapper.deleteDishById(ids);
		dishFlavorMapper.deleteDishFlavorByDishId(ids);

		return Result.success("删除成功");
	}

	/**
	 * 根据ID查询菜品
	 *
	 * @return:
	 * @param:
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Result<DishVO> getDishAndFlavorsById(Long id) {
		// 参数校验
		if (Objects.isNull(id)) {
			throw new ParamsIllegalException("修改失败，无效的菜品信息");
		}

		// 业务处理
		// 1. 查询菜品基本数据及其口味数据
		DishVO dishVO = dishMapper.selectDishAndFlavorsById(id);

		return Result.success(dishVO);
	}

	/**
	 * 更新菜品及其口味
	 *
	 * @return:
	 * @param:
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Result<String> updateDishAndFlavors(DishDTO dishDTO) {
		// 参数校验
		if (Objects.isNull(dishDTO) ||
			Objects.isNull(dishDTO.getId()) ||
			Objects.isNull(dishDTO.getCategoryId()) ||
			StringUtils.isBlank(dishDTO.getName()) ||
			Objects.isNull(dishDTO.getPrice()) ||
			StringUtils.isBlank(dishDTO.getImage())) {
			throw new ParamsIllegalException("修改菜品信息出错了，请重新输入");
		}

		// 业务处理
		// 1. 查询菜品是否存在
		Integer count = dishMapper.countById(dishDTO.getId());
		if (count == 0) {
			throw new DishExistsException("菜品不存在，请联系管理员");
		}
		// 2. 更新菜品信息
		Dish dish = new Dish();
		BeanUtils.copyProperties(dishDTO, dish);
		dishMapper.updateDishById(dish);
		// 3. 更新菜品口味信息（先删后加）
		dishFlavorMapper.deleteDishFlavorById(dishDTO.getId());
		List<DishFlavor> flavors = dishDTO.getFlavors();
		if (Objects.isNull(flavors)) {
			return Result.success();
		}
		flavors.forEach(flavor -> flavor.setDishId(dish.getId()));
		dishFlavorMapper.insertDishFlavor(flavors);

		return Result.success("菜品信息修改成功");
	}

	/**
	 * 根据分类ID查询所有菜品
	 *
	 * @return:
	 * @param:
	 */
	@Override
	public Result<List<Dish>> findAllDish(Long categoryId) {
		// 参数校验
		if (Objects.isNull(categoryId)) {
			throw new ParamsIllegalException("查询失败，无效的分类信息");
		}

		// 业务处理
		List<Dish> dishes = dishMapper.findAllDish(categoryId);

		return Result.success(dishes);
	}

	/**
	 * 根据ID更新菜品状态
	 *
	 * @return:
	 * @param:
	 */
	@Override
	public Result<String> updateDishStatus(Long status, Integer id) {
		// 参数校验
		if (Objects.isNull(status) || Objects.isNull(id) || (status != 1 && status != 0)) {
			throw new ParamsIllegalException("修改失败，无效的菜品状态信息");
		}

		// 业务处理
		dishMapper.updateDishStatus(status, id);


		return Result.success("菜品状态修改成功");
	}

}
